package com.kj.tms.system.controller.user;


import com.kj.tms.common.bean.controller.BasicController;
import com.kj.tms.common.bean.dto.Pager;
import com.kj.tms.common.bean.dto.ReturnData;
import com.kj.tms.common.bean.redis.RedisAccessImpl;
import com.kj.tms.common.bean.session.SessionManager;
import com.kj.tms.common.utils.StringUtil;
import com.kj.tms.common.utils.constant.Consts;
import com.kj.tms.common.utils.encrypt.MD5Util;
import com.kj.tms.pri.system.org.dto.OrgDto;
import com.kj.tms.pri.system.role.dto.RoleDto;
import com.kj.tms.pri.system.user.dto.UserDto;
import com.kj.tms.pri.system.user.dto.UserOrgDto;
import com.kj.tms.pri.system.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wzl on 2017/10/12.
 * 用户管理类
 */
@RestController
@RequestMapping("/system/user")
public class UserController extends BasicController {


    @Autowired
    private UserService userService;

    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private RedisAccessImpl redisAccessImpl;

    @RequestMapping(value = "/getAll")
    public String getAll() throws Exception {
        List<UserDto> list = userService.getAll();
        return list.toString();
    }

    @RequestMapping(value = "/first", method = RequestMethod.GET)
    public Map<String, Object> firstResp(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        sessionManager.setAttribute("request Url", request.getRequestURL());
        map.put("request Url", request.getRequestURL());
        redisAccessImpl.set("SESSION", sessionManager.getId());
        return map;
    }

    @RequestMapping(value = "/sessions", method = RequestMethod.GET)
    public Object sessions(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("sessionId", sessionManager.getId());
        map.put("message", sessionManager.getAttribute("test"));
        map.put("sessionIdrRdis", redisAccessImpl.get("SESSION"));
        return map;
    }

    /**
     * 进入到用户主页面
     *
     * @return 登录page
     */
    @RequestMapping(value = "/index")
    public ModelAndView toLogin() {
        return new ModelAndView("system/user/index");
    }

    /**
     * 进入添加用户页面
     *
     * @return ModelAndView
     * @throws
     */
    @RequestMapping("/toAdd")
    public ModelAndView toAdd() {
        return new ModelAndView("system/user/add");
    }

    /**
     * @param
     * @return ModelAndView
     * @throws
     * @method [orgRoleAllot]
     * @description [机构角色分配]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月12日 17:38
     */
    @RequestMapping("/orgRoleAllot")
    public ModelAndView orgRoleAllot() {
        return new ModelAndView("system/user/roleAssignment");
    }

    /**
     * 进入用户信息修改页面
     *
     * @return ModelAndView
     */
    @RequestMapping("/toUpdate")
    public ModelAndView toUpdate() {
        return new ModelAndView("system/user/update");
    }

    /**
     * @param model 用户信息
     * @return
     * @throws
     * @method [list]
     * @description [显示全部用户]
     * @author 王国庆
     * @version 1.0
     * @date 2018年01月03日 11:36
     */
    @RequestMapping("/list")
    public ReturnData list(UserDto model) {

        // 设置页面数据
        Pager pager = new Pager();
        try {
            pager = userService.listUser(model);
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "查询全部用户失败", "");
        }
        Map<String, Object> returnObject = new HashMap<>();
        returnObject.put("total", pager.getRowCount());
        returnObject.put("rows", pager.getResults());
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }

    /**
     * @param
     * @return
     * @throws
     * @method [queryOrgByList]
     * @description [模糊匹配查询机构数据到列表]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月28日 14:22
     */
    @RequestMapping("/queryOrgByList")
    public ReturnData queryOrgByList(OrgDto model) {

        List<OrgDto> dataList = null;
        try {
            dataList = userService.queryOrgByList(model);
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "查询机构数据到列表失败", "");
        }
        //设置页面数据
        Map<String, Object> returnObject = new HashMap<String, Object>();
        returnObject.put("rows", dataList);
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }


    /**
     * @param roleNames 角色名称数组 以,分开
     * @return ReturnData
     * @throws
     * @method [queryMutexByRoleNames]
     * @description [根据角色名称查询互斥角色]
     * @author 王国庆
     * @version 1.0
     * @date 2018年01月08日 16:50
     */
    @RequestMapping("/queryMutexByRoleNames")
    public ReturnData queryMutexByRoleNames(@RequestParam(value = "roleNames", required = false) String roleNames) {
        ReturnData msg = new ReturnData();
        try {
            msg = userService.queryMutexByRoleNames(roleNames);
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "查询互斥角色异常。", "");
        }
        return msg;
    }


    /**
     * @param orgRoleList
     * @return
     * @throws
     * @method [save]
     * @description [保存用户信息]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月22日 15:53
     */
    @RequestMapping("/save")
    public ReturnData save(@RequestParam(value = "orgRoleList", required = false) String orgRoleList,
                           HttpServletRequest request) {

        Map<String, String> returnObject = new HashMap<>();
        try {
            Map<String, String> requestParameters = super.getRequestParameters(request);
            if (!StringUtil.isEmptyOrNull(orgRoleList)) {
                userService.save(requestParameters, orgRoleList);
            }
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "添加用户失败，请联系管理人员。", returnObject);
        }
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }

    /**
     * 删除用户
     *
     * @param dto 参数
     * @return ReturnData
     */
    @RequestMapping("/delete")
    public ReturnData delete(UserDto dto) {
        Map<String, Object> returnObject = new HashMap<>();
        dto.setDelMark(Consts.DEL_MARK_1);
        try {
            userService.delete(dto);
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "删除用户失败，请联系管理人员。", returnObject);
        }
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }

    /**
     * @param orgRoleList
     * @return
     * @throws
     * @method [update]
     * @description [更新用户信息]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月22日 15:53
     */
    @RequestMapping("/update")
    public ReturnData update(@RequestParam(value = "orgRoleList", required = false) String orgRoleList,
                             HttpServletRequest request) {

        Map<String, String> returnObject = new HashMap<>();
        try {
            Map<String, String> requestParameters = super.getRequestParameters(request);
            if (!StringUtil.isEmptyOrNull(orgRoleList)) {
                userService.update(requestParameters, orgRoleList);
            }
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "修改用户失败，请联系管理人员。", returnObject);
        }
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }

    /**
     * @param userDto 用户信
     * @param type    方法类型
     * @return ReturnData
     * @throws
     * @method [listOrgRole]
     * @description [加载配置机构权限信息]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月11日 17:35
     */
    @RequestMapping("/listOrgRole")
    public ReturnData listOrgRole(UserDto userDto,
                                  @RequestParam(value = "type", required = false) String type) {
        List<UserOrgDto> userOrgDtoList = new ArrayList<UserOrgDto>();
        ;
        if ("update".equals(type)) {
            try {
                userOrgDtoList = userService.listOrgRoleByPage(userDto);

            } catch (Exception e) {
                return new ReturnData(Consts.ERROR, "查询用户权限管理机构下的角色配置信息分页数据失败", "");
            }
        }
        // 设置页面数据
        Map<String, Object> returnObject = new HashMap<String, Object>();
        returnObject.put("rows", userOrgDtoList);

        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }


    /**
     * @param userDto 用户信
     * @param orgCode 机构编码
     * @param orgName 机构名称
     * @return ReturnData
     * @throws
     * @method [listOrgByUserOrgPage]
     * @description [根据当前机构加载配置机构权限分页信息]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月14日 16:12
     */
    @RequestMapping("/listOrgByUserOrgPage")

    public ReturnData listOrgByUserOrgPage(UserDto userDto,
                                           @RequestParam(value = "orgCode", required = false) String orgCode,
                                           @RequestParam(value = "orgName", required = false) String orgName) {
        List<UserOrgDto> userOrgDtoList = new ArrayList<UserOrgDto>();
        try {
            userOrgDtoList = userService.listOrgByUserOrgPage(userDto, orgCode, orgName);
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "根据当前机构加载配置机构权限分页数据失败", "");
        }
        // 设置页面数据
        Map<String, Object> returnObject = new HashMap<String, Object>();
        return new ReturnData(Consts.SUCCESS, "", userOrgDtoList);
    }

    /**
     * @param dto
     * @return ReturnData
     * @throws
     * @method [listOrg]
     * @description [方法描述]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月12日 17:53
     */
    @RequestMapping("/listOrg")
    public ReturnData listOrg(OrgDto dto) {
        Pager pager = new Pager();
        try {
            pager = userService.listOrg(dto);
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "查询机构角色信息失败", "");
        }
        // 设置页面数据
        Map<String, Object> returnObject = new HashMap<String, Object>();
        returnObject.put("total", pager.getRowCount());
        returnObject.put("rows", pager.getResults());
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }


    /**
     * 导出用户信息excel
     *
     * @param userDto  请求参数
     * @param response http回复
     */
    @RequestMapping("/exportData")
    public ResponseEntity<byte[]> exportData(UserDto userDto,
                                             HttpServletResponse response) {
        return userService.exportData(userDto);
    }

    @RequestMapping("/initRole")
    public ReturnData initRole(@RequestParam(value = "roleId", required = false) String roleId) {

        Map<String, Object> returnObject = new HashMap<>();
        List<RoleDto> initRoleList = new ArrayList<RoleDto>();
        try {
            //可从redis中获取
            initRoleList = userService.initRole(roleId);

        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "获取用户角色信息失败。", returnObject);
        }
        returnObject.put("total", initRoleList.size());
        returnObject.put("rows", initRoleList);
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }

    /**
     * @param dto 用户信息
     * @return
     * @throws
     * @method [updateValidMark]
     * @description [用户禁用启用]
     * @author 王国庆
     * @version 1.0
     * @date 2017年12月22日 15:21
     */
    @RequestMapping("/updateValidMark")
    public ReturnData updateValidMark(UserDto dto) {

        Map<String, Object> returnObject = new HashMap<>();
        try {
            userService.update(dto);
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "用户禁用启用失败,请联系管理人员。", returnObject);
        }
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }

    /**
     * 密码重置
     *
     * @param dto 用户信息dto
     * @return ReturnData
     */
    @RequestMapping("/backPwd")
    public ReturnData backPwd(UserDto dto) throws Exception {
        Map<String, Object> returnObject = new HashMap<>();
        dto.setPassword(MD5Util.getMD5Code(Consts.PASSWORD_INITIAL));
        try {
            userService.update(dto);
        } catch (Exception e) {
            return new ReturnData(Consts.ERROR, "密码重置失败", returnObject);
        }
        return new ReturnData(Consts.SUCCESS, "", returnObject);
    }

}